package org.snlab.util;

import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.snlab.compiler.DdmdConf;
import org.snlab.compiler.DdmdConfs;
import org.snlab.proto.RuntimeGrpc;
import org.snlab.proto.RuntimeGrpc.RuntimeBlockingStub;
import org.snlab.proto.RuntimeGrpc.RuntimeStub;
import org.snlab.runtime.Config;
import org.snlab.runtime.Daemon;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class Replay {
    public static boolean isReplay = false;
    public static RuntimeBlockingStub fakeStub = null;

    public static void main(String[] args) {
        isReplay = true;
        Options options = new Options();
        options.addOption("e", true, "Env dir");
        options.addOption("s", true, "Simulated switch");
        options.addOption("f", true, "Fake server addr");
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd;
        
        try {
            cmd = parser.parse(options, args);

            if (cmd.hasOption("f")) {
                ManagedChannel c = ManagedChannelBuilder.forTarget(cmd.getOptionValue("f"))
                        .usePlaintext().build();
                fakeStub = RuntimeGrpc.newBlockingStub(c);
            }

            DdmdConfs ddmdConfs = new DdmdConfs();
            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
            ddmdConfs = objectMapper.readValue(new File(cmd.getOptionValue("e") + "/gen/ddmdconfs.yaml"), DdmdConfs.class);
            System.out.println("Using env " + cmd.getOptionValue("e"));
            for (DdmdConf ddmdConf : ddmdConfs.getDdmdConfs()) {
                if (!ddmdConf.getName().equals(cmd.getOptionValue("s"))) {
                    continue;
                }
                Config config = new Config();
                config.setName(ddmdConf.getName());
                config.setPort(ddmdConf.getPort());
                config.setFib(ddmdConf.getFib());
                config.setEnvDir(cmd.getOptionValue("e"));
                Daemon daemon = new Daemon(config);
                daemon.run();
            }
            
            System.out.println("eof");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
